package com.baidu.sggc.core.common.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class TokenUtils {

  @Value("${third.mb.ak}")
  private  String ak;

  @Value("${third.mb.sk}")
  private  String sk;


  @Value("${third.ab.X-Authorization}")
  private String xAuthorization;

  @Value("${third.ab.Authorization}")
  private String authorization;

  private static final String X_BCE_REQUEST_ID = "X-Bce-Request-ID";
  private static final String SIGN_TIME = "Sign-Time";
  private static final String X_BCE_REQUEST_ACCESS_ADDRESS = "X-Bce-Request-Access-Address";
  private static final String ACCESS_KEY = "Access-Key";
  private static final String TOKEN = "Token";


  public  HttpHeaders getHeaders(String url , String requestBody) {
    HttpHeaders headers = new HttpHeaders();
    String requestId = UUID.randomUUID().toString();
    headers.add(X_BCE_REQUEST_ID, requestId);
// set sign time // set sign time
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String now = formatter.format(new Date());
    headers.add(SIGN_TIME, now);
    headers.add(X_BCE_REQUEST_ACCESS_ADDRESS , url);
    headers.add(ACCESS_KEY, ak);
// set request id // set request id
    String signInfo = requestBody == null ? "" : requestBody;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(signInfo);
    stringBuilder.append(sk);
    stringBuilder.append(requestId);
    stringBuilder.append(now);
    MessageDigest messageDigest;
    String encodeStr = "";
    try {
      messageDigest = MessageDigest.getInstance("SHA-256");
      byte[] hash = messageDigest.digest(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
      encodeStr = String.valueOf(Hex.encodeHex(hash));
    } catch (NoSuchAlgorithmException e) {
      log.error("getAccessToken error", e);
    }
    headers.add(TOKEN, encodeStr);
    return headers;
  }

  public  HttpHeaders getABHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-Authorization" , xAuthorization);
    headers.add("Authorization" , authorization);
    headers.add("Content-Type" , "application/json");
    return headers;
  }

}
